<script setup lang="ts">
import type { EChartsOption } from 'echarts';

import { onMounted, onUnmounted, ref, watch } from 'vue';

import * as echarts from 'echarts';

const props = defineProps<{
  chartData: {
    indicators: Array<{
      max: number;
      name: string;
    }>;
    series: {
      data: Array<{
        name: string;
        value: number[];
      }>;
      type: string;
    }[];
  };
}>();

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

const getOptions = (): EChartsOption => {
  // 确保数据存在
  const seriesData = props.chartData.series?.[0]?.data?.[0] || {
    value: [],
    name: '爱好分布',
  };

  return {
    backgroundColor: 'transparent',
    radar: {
      indicator: props.chartData.indicators || [],
      shape: 'polygon',
      splitNumber: 4,
      axisName: {
        color: '#8AB5E9',
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(138, 181, 233, 0.3)',
        },
      },
      splitArea: {
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(138, 181, 233, 0.3)',
        },
      },
    },
    series: [
      {
        type: 'radar',
        data: [
          {
            value: seriesData.value,
            name: seriesData.name,
            itemStyle: {
              color: '#FF6B3D',
            },
            lineStyle: {
              color: '#FF6B3D',
            },
            areaStyle: {
              color: 'rgba(255, 107, 61, 0.3)',
            },
          },
        ],
      },
    ],
  };
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  try {
    chart = echarts.init(chartRef.value);
    const options = getOptions();
    console.log('Chart options:', options);
    chart.setOption(options);
  } catch (error) {
    console.error('Chart initialization error:', error);
  }
};

// 监听数据变化
watch(
  () => props.chartData,
  () => {
    try {
      const options = getOptions();
      console.log('Updated chart options:', options);
      chart?.setOption(options);
    } catch (error) {
      console.error('Chart update error:', error);
    }
  },
  { deep: true },
);

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
});
</script>

<template>
  <div ref="chartRef" :style="{ width: '100%', height: '250px' }"></div>
</template>
